package com.sunl.mall.common.util;

import com.sunl.mall.common.error.ErrorCodeEnum;
import com.sunl.mall.common.response.CommonResponse;

public class ResponseManage {
    private ResponseManage() {
    }

    /**
     * 即使对象为null也返回成功状态
     *
     * @param result
     * @param <T>
     * @return
     */
    public static <T> CommonResponse<T> success(T result) {
        CommonResponse<T> response = new CommonResponse<>();
        response.setResult(result);
        response.setSuccess(true);
        return response;
    }

    public static <T> CommonResponse<T> successIfNotNull(T result) {
        CommonResponse<T> response = new CommonResponse<>();
        response.setResult(result);
        if (response.isSuccess()) {
            response.setError(ErrorCodeEnum.SUCCEED_CODE);
        } else {
            response.setError(ErrorCodeEnum.BIZ_ERROR);
        }
        return response;
    }

    public static <T> CommonResponse<T> successIfNotNull(T result, String nullMsg) {
        CommonResponse<T> response = new CommonResponse<>();
        response.setResult(result);
        if (response.isSuccess()) {
            response.setError(ErrorCodeEnum.SUCCEED_CODE);
        } else {
            if (CollectionUtil.isEmpty(nullMsg)) {
                response.setErrorMsg(ErrorCodeEnum.BIZ_ERROR.getErrorDesc());
            } else {
                response.setErrorMsg(nullMsg);
            }
            response.setErrorCode(ErrorCodeEnum.BIZ_ERROR.getErrorCode());
        }
        return response;
    }

    public static <T> CommonResponse<T> fail(String message) {
        CommonResponse<T> response = new CommonResponse<>();
        response.setErrorCode(ErrorCodeEnum.BIZ_ERROR.getErrorCode());
        if (CollectionUtil.isEmpty(message)) {
            response.setErrorMsg(ErrorCodeEnum.BIZ_ERROR.getErrorDesc());
        } else {
            response.setErrorMsg(message);
        }
        return response;
    }

    public static <T> CommonResponse<T> fail(ErrorCodeEnum error) {
        CommonResponse<T> response = new CommonResponse<>();
        response.setError(error);
        return response;
    }

    public static <T> CommonResponse<T> fail(int errorCode, String message) {
        CommonResponse<T> response = new CommonResponse<>();
        response.setErrorCode(errorCode);
        response.setErrorMsg(message);
        return response;
    }

}
